/**
 * Created by wangxin on 2017-9-26 10:02:01.
 */

'use strict';
const page = {
    countNum:$('.countNum'),
    eventStart:$('.eventStart'),
    eventEnd:$('.eventEnd'),
    receiveDate:$('#receiveDate'),
    limit:$('#limit'),
    drawPrice:$('#drawPrice'),
    couponPrize:$('.couponPrize'),
    url : {
        loadEventRule:contextData.contextPath+'/work/loadEventRule',
        getResult:contextData.contextPath+'/work/getResult'
    },
    active:null,
    _id : null,
    list : null,
    drawFlag : true,
    dateFlag : false,
};

page.init = function () {
    page.initElement();
    page.initEvent();
};

page.initElement = function () {
    const thisPage = this;
    Dolphin.ajax({
        url: thisPage.url.loadEventRule,
        type: "get",
        forceUrl: 'true',
        data: {eventId: contextData.data.eventId,gameType:'egg'},
        onSuccess: function (data) {
            if(data.err){
                alert(data.err);
            }else{
                var createOrgCode = contextData.userData && contextData.userData.createOrgCode || null;
                var store = data && data.store || null;
                if(!(!createOrgCode || !store || (store && !store.length) || store.find(o=>o.code === createOrgCode))){
                    var bg = $("<div style='position:fixed;top: 0;bottom:0;left:0;right:0;text-align: center;padding-top:90%;font-weight:700;color: white;font-size:24px;background: rgba(55,55,55,0.75)'>您不能参加本次活动" +
                        "<br />请咨询相关门店人员</div>");
                    $("body").append(bg);
                }

                $(document).attr("title",data.event.eventName);
                var ruleList = data.rule,
                    today = new Date(),
                    eds = data.event.eventDateStart,
                    ede = data.event.eventDateEnd;
                thisPage.countNum.html(sessionStorage.getItem('currPoint')||contextData.userData.currPoint);

                if(data.event.limitNum===null){
                    $('.curCount').html('不限')
                }else{
                    var remainNum = data.event.limitNum - data.count;
                    if(remainNum>0){
                        $('.curCount').html(remainNum);
                    }else{
                        $('.curCount').html(0);
                        page.drawFlag = false;
                    }
                }

                thisPage.eventStart.html(thisPage.formatterDate(eds));
                thisPage.eventEnd.html(thisPage.formatterDate(ede));
                thisPage.receiveDate.html(thisPage.formatterDate(data.event.receiveDate));
                thisPage.limit.html(data.event.limitNum);
                if(today<=new Date(ede)&&today>=new Date(eds)){
                    page.dateFlag = true;
                }
                for (var i = 0; i < ruleList.length; i++) {
                    if (ruleList[i].prizeType === 'point') {
                        ruleList[i].prizeType = '积分';
                    } else if (ruleList[i].prizeType === 'coupon') {
                        ruleList[i].prizeType = '礼券';
                    } else if (ruleList[i].prizeType === 'prize') {
                        ruleList[i].prizeType = '实物';
                    }
                }
                $('#retail').append(data.event.intro);
                new Vue({
                    el: '.tableList',
                    data:{
                        rules: data.rule,
                    },
                });
            }
        },
        onError: function (e) {
            alert('网络出错啦，请您重新加载');
        }
    });
};

page.initEvent = function () {
    const thisPage = this;
    $(document).ready(function(){
        //加载完成之后关闭loading
        $('.loadingDiv').hide();
        //点击抽奖
        $('body').on('click','.list_EggsDiv ul li img',function(){
            if(!page.drawFlag){
                alert('砸的次数达到上限啦~休息一下吧')
            }else{
                if(!$(this).attr('drawFlag')){
                    $(this).attr('drawFlag',true);
                    var id = $(this).attr('id');
                    var active = $('#'+id);
                    page.clickDan(active);   //砸蛋
                    thisPage.active = $('#'+id);
                }/*else {
                    page.clickDan(active);   //砸蛋
                    // alert('换个蛋来砸吧:)')
                }*/
            }
        });

        //关闭抽奖结果
        $('body').on('click','.colseJiangPin,.closeModels',function(){
            $('.bg-mask').remove();
            $('.jiangPinResult').remove();
            $('body').css({"overflow":"visible"});
            thisPage.active.attr('src',contextData.contextPath+'/images/egg.png')
        });

        //登录
        $('body').on('click','.tishiChouJiang .loginSpan',function(){
            alert.alertLogin();
        });

        //关闭登录窗口

        //关闭默认的事件动作
        $('body').on('touchmove','.bg-mask',function(event) { event.preventDefault(); }, false);
        $('body').on('touchmove','.loadingDiv',function(event) { event.preventDefault(); }, false);
    });

};

page.formatterDate = function (val, formatter) {
    if(val){
        var date = Dolphin.string2date(val, "yyyy-MM-ddThh:mm:ss.");
        date.setHours(date.getHours() + 8);
        return Dolphin.date2string(date, formatter || "yyyy-MM-dd");
    }else{
        return '';
    }
};

page.clickDan = function(active){
    var result;
    if(page.dateFlag){
        if(page.drawFlag){
            Dolphin.ajax({
                url: page.url.getResult,
                type: "get",
                forceUrl: 'true',
                async: false,
                data: {eventId: contextData.data.eventId,gameType:'egg'},
                onSuccess: function (data) {
                    console.log(data);
                    result = data;
                    if(result.err){
                        console.log(result.err);
                        alert(result.err)
                    }else{
                        page.clickJinDanView(active,result);
                        page.countNum.html(parseInt(data.addMsg.curUserPoint));

                        if(data.result.limitNum===null){
                            $('.curCount').html('不限');
                        }else{
                            var remainNum = (data.result.limitNum||data.result.eventId.limitNum) - data.count;
                            if(remainNum > 0){
                                $('.curCount').html(remainNum);
                                page.countNum.html(parseInt(data.addMsg.curUserPoint));
                                sessionStorage.setItem('currPoint',parseInt(data.addMsg.curUserPoint))
                            }else if(remainNum==0){
                                page.drawFlag = false;
                                $('.curCount').html(0);
                            }
                        }


                        // if(remainNum > 0){
                        //     page.countNum.html(parseInt(data.addMsg.curUserPoint));
                        //     sessionStorage.setItem('currPoint',parseInt(data.addMsg.curUserPoint))
                        // }else{
                        //     page.drawFlag = false;
                        //     page.countNum.html(0);
                        // }
                    }

                },
                onError: function (e) {
                    $.toast("网络出错啦，请重新加载:)", "text");
                }
            });
        }
    }else{
        alert('亲~，活动不再有效期内，尽情期待...')
    }
};

page.jiangPinResult = function(active,data){
    var str;
    if (data.result.eventId) {
        var result = data.result;
        var prizeName;
        console.log(data.result);
        if(result.prizeType=='point'){
            prizeName = '获得积分:'+result.point
        }else if(result.prizeType=='coupon'){
            prizeName = '获得礼券:'+result.giftName
        }else{
            prizeName = '获得奖品:'+result.priceName
        }
        str = '';
        str += '<div class="bg-mask"></div>';
        str +='<div class="jiangPinResult">';
        str +='<div class="modelTitles">恭喜您，中奖啦~</div>'
        str +='<div class="huojiangxinxi">';
        str+=' <div style="color: white;font-size: 18px">'+data.result.rule+'</div> <div class="center" style="font-size: 14px;color: white;margin-top: 15px" >'+prizeName+'</div>'
        str+=' </div>';
        str +='<img class="imgJiangPin"  src="'+ contextData.contextPath+'/images/zhongla.png" alt="奖品">';
        str +='<img class="colseJiangPin"  src="'+ contextData.contextPath+'/images/close.png" alt="关闭">';
        str+='  <div class="weui-flex buttonGroup">' +
            '            <div class="weui-flex__item">' +
            '                <div class="myPrice">' +
            '                    <a href= "'+contextData.contextPath+'/view/prize/prizeRecord?openId='+contextData.body.openId  +'&publicId='+ contextData.body.publicId +'&eventId='+contextData.data.eventId+'" >' +
            '                        <div class="btn">' +
            '                            我的奖品' +
            '                        </div>' +
            '                    </a>' +
            '                </div>' +
            '            </div>' +
            '            <div class="weui-flex__item">' +
            '                <div class="drawAgain">' +
            '                    <div class="btn closeModels" onclick= page.close>' +
            '                        再来一次' +
            '                    </div>' +
            '                </div>' +
            '            </div>' +
            '        </div>';
        str +='</div>';
    } else {
        str = '';
        str += '<div class="bg-mask"></div>';
        str +='<div class="jiangPinResult">';
        str +='<div class="modelTitles">很遗憾，未中奖</div>'

        str +='<img class="imgJiangPin"  src="'+ contextData.contextPath+'/images/weizhongjiang.png" alt="奖品">';
        str +='<img class="colseJiangPin"  src="'+ contextData.contextPath+'/images/close.png" alt="关闭">';
        str+='  <div class="weui-flex buttonGroup">' +
            '            <div class="weui-flex__item">' +
            '                <div class="myPrice">\n' +
            '                    <a href= "'+contextData.contextPath+'/view/prize/prizeRecord?openId='+ contextData.body.openId +'&publicId='+ contextData.body.publicId +'" >' +

            '                        <div class="btn">\n' +
            '                            我的奖品\n' +
            '                        </div>\n' +
            '                    </a>\n' +
            '                </div>\n' +
            '            </div>\n' +
            '            <div class="weui-flex__item">\n' +
            '                <div class="drawAgain">\n' +
            '                    <div class="btn closeModels">\n' +
            '                        再来一次\n' +
            '                    </div>\n' +
            '                </div>\n' +
            '            </div>\n' +
            '        </div>'+
            '</div>'
    }


    $('body').css({'overflow':'hidden'});
    $('body').prepend(str);
    active.removeAttr('drawFlag');
    setTimeout(function(){
        $('.jiangPinResult').addClass('active');
        active.attr('src',contextData.contextPath+'/images/jiangpin.png')

    },200);
};
page.clickJinDanView = function(active,result){
    var str = '';
    str += '<div class="bg-mask"></div>';
    str +='<div class="chouJiang">';
    str +='<p class="chouJiangTishi">请稍等...</p>';
    str +='<img class="caiDai" src="' + contextData.contextPath+'/images/caidai.png" alt="彩带">';
    str +='<img class="imgDan"  src="'+ contextData.contextPath+'/images/egg.png" alt="砸蛋" title="砸蛋">';
    str +='<img class="imgChuiZi"  src="'+ contextData.contextPath+'/images/chuizi.png" alt="锤子">';
    str +='</div>';
    $('body').css({'overflow':'hidden'});
    $('body').prepend(str);

    setTimeout(function(){
        $('.bg-mask').remove();
        $('.chouJiang').remove();
        if(result){
            page.jiangPinResult(active,result);
        }else{
            $.toast("网络出错啦，请重新加载:)", "text");
        }

    },3500);
}

page.formatterDate = function (val, formatter) {
    if(val){
        return Dolphin.date2string(Dolphin.string2date(val, "yyyy-MM-ddThh:mm:ss."), formatter || "yyyy-MM-dd");

    }
};
page.close = function () {
    $('.bg-mask').remove();
    $('.inputInfo').remove();
    $('body').css({"overflow":"visible"});
    thisPage.active.attr('src',contextData.contextPath+'/images/egg.png')
}
$(function () {
    page.init();
});



